<template>
  <el-button 
  type="primary" 
  size="default" 
  @click="emit('setState',1)" 
  icon="ele-Plus"
  :disabled="!category3Id"
    >添加SPU</el-button
  >

  <el-table :data="spuPageList" border stripe :style="{ margin: '30px 0 ' }">
    <el-table-column type="index" width="80" label="序号" />
    <el-table-column label="SPU名称" prop="spuName"> </el-table-column>
    <el-table-column label="SPU描述" prop="description"> </el-table-column>
    <el-table-column label="操作">
      <template v-slot="{row ,$index}">
        <el-button type="primary"  @click="addSku" icon="ele-Plus" title="添加SKU"></el-button>
        <el-button 
        type="primary"  
        @click="emit('setState',1,row)" 
        icon="ele-Edit" 
        title="编辑SPU"
        ></el-button>
        <el-button type="info"  @click="" icon="ele-Warning" title="查看SKU"></el-button>
        <el-button type="danger"  @click="deleteSpu(row)" icon="ele-Delete" title="删除SPU"></el-button>
      </template>

    </el-table-column>
  </el-table>

  <el-pagination
    v-model:page-size="limit"
    v-model:current-page="page"
    :page-sizes="[3, 5, 7, 9]"
    :pager-count="5"
    layout="prev, pager, next, sizes"
    :total="total"
  />
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "SpuList",
});
</script>

<script setup lang="ts">
import { ref, watch } from "vue";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";

import useAttrStore from "@/stores/attr";
import { requestSpuList ,requestDeleteSpu} from "@/api/spu";
import type { SpuInfoType } from "@/api/spu";
//拿到自定义事件得函数
 const emit = defineEmits<{
  (event:"setState",state:number,row?:SpuInfoType):void
}>()
//初始化页码的数据
const limit = ref(3);
const page = ref(1);
const total = ref(0);

//拿到pinia中的数据
const arrtStore = useAttrStore()
//解构数据
const {category3Id} = storeToRefs(arrtStore)
//声明一个数据
const spuPageList = ref<SpuInfoType[]>([])
//发送spu分页列表
const getSpuPageList =async ()=>{
  try {
    const result = await requestSpuList(
      page.value,
      limit.value,
      category3Id.value as number
    )
    //把数据中得总数和分类列表给响应式
    spuPageList.value = result.records
    total.value = result.total
  } catch (error) {
    ElMessage.error("请求分页列表失败");
  }
}
//当category3Id改变时 发送i请求、
watch(
  category3Id,
  ()=>{
    if(category3Id.value ===null){
      //清空列表 不发送请求
      spuPageList.value = []
      total.value = 0
      return 
    }

    //有变化就发请求
    getSpuPageList()
  },
  {immediate:true}
)
//监听 当数据该百年分页器的时候重新发送数据
watch([limit,page],()=>{
      //有变化就发请求
      getSpuPageList()
})

//点击删除spu列表
const  deleteSpu=async (row:SpuInfoType)=>{
  try {
    await requestDeleteSpu(row.id as number)
    ElMessage.success("删除spu成功");
  } catch (error) {
    ElMessage.error("删除spu失败");
  }
  //然后重新更新视图
      //有变化就发请求
      getSpuPageList()
}

//点击添加sku跳转到sku
const addSku=()=>{
  
    emit("setState",2)
}
</script>

